package com.knowvoyage.knowvoyageserver.service.Impl;

import com.knowvoyage.knowvoyageserver.mapper.UserMapper;
import com.knowvoyage.knowvoyageserver.pojo.dto.LoginDTO;
import com.knowvoyage.knowvoyageserver.pojo.dto.RegisterDTO;
import com.knowvoyage.knowvoyageserver.pojo.entity.User;
import com.knowvoyage.knowvoyageserver.pojo.vo.Result;
import com.knowvoyage.knowvoyageserver.service.AuthService;
import com.knowvoyage.knowvoyageserver.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {
    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;

    @Override
    public Result<String> register(RegisterDTO registerDTO) {
        log.info("用户注册service调用，用户: {}",registerDTO.getPhone());
        if (userMapper.selectByPhone(registerDTO.getPhone()) != null) {
            return Result.error(1, "手机号已注册");
        }

        User user = new User();
        user.setPhone(registerDTO.getPhone());
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
        user.setName(registerDTO.getName());
        user.setCreateTime(LocalDateTime.now());
        userMapper.insert(user);

        return Result.success("注册成功");
    }

    @Override
    public Result<Map<String, Object>> login(LoginDTO loginDTO) {
        log.info("用户登录service调用，用户: {}",loginDTO.getPhone());
        User user = userMapper.selectByPhone(loginDTO.getPhone());
        if(user == null) {
            return Result.error( 400,"用户不存在");
        }

        if (!passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            return Result.error(400,"密码错误");
        }

        String token = jwtUtil.generateToken(user.getPhone(), user.getUserId());
        Map<String, Object> data = Map.of(
                "token", token,
                "user", user
        );
        return Result.success(data);
    }
}
